<template>
	<view class="page">
		<!-- 地址 -->
		<view class="address-data" v-if="goodsInfor.goods.is_address==1">
			<view class="address-list flex-box" v-if="addressInfor.mobile" @click="onSkip('address')">
				<view class="box-1">
					<view class="list">
						<text class="address">{{addressInfor.province+addressInfor.city+addressInfor.district}}{{addressInfor.address || ''}}</text>
					</view>
					<view class="list">
						<text>{{addressInfor.uname}}</text>
						<text>{{addressInfor.mobile}}</text>
					</view>
				</view>
				<u-icon name="arrow-right" size="24" color="#c5c5c5"></u-icon>
			</view>
			<view class="n-address" v-else>
				<view class="a-1 flex-box" @click="onSkip('address')">
					<view class="box-1">添加收货地址</view>
					<u-icon name="arrow-right" size="24" color="#c5c5c5"></u-icon>
				</view>
			</view>
			<image src="@/static/img/address-line.png" class="bar-line"></image>
		</view>
		<!-- 商品 -->
		<view class="goods-content">
			
		<view class="goods-data">
			<view class="goods-list">
				<view class="list">
					<view class="thumb">
						<image :src="goodsInfor.goods.imglogo" mode=""></image>
					</view>
					<view class="item">
						<view class="title">
							<text class="name one-omit">{{goodsInfor.goods.title}}</text>
						</view>
						<view class="price-number flex-box">
							<view class="price box-1">
								<text class="min">￥</text>
								<text class="max">{{goodsInfor.goods.price || 0}}</text>
							</view>
							<view class="number flex-box">
								<u-icon name="minus" color="#333" @tap="cutFun"></u-icon>
								<input class="count-input" v-model="num" type="number" @input="numFun" value="1" />
								<u-icon name="plus" color="#333" @tap="addFun"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
		
		</view>
		<!-- 订单金额 -->
		<view class="order-price" v-if="goodsInfor.allow_pay_type !='transfer_parent'">
			<view class="price-list">
				<view class="list">
					<view class="title">
						<text>商品金额</text>
					</view>
					<view class="price">
						<text>￥{{goodsInfor.total_price || ''}}</text>
					</view>
				</view>
				<view class="list">
					<view class="title">
						<text>运费</text>
					</view>
					<view class="price">
						<text>￥0.00</text>
					</view>
				</view>
				<div class="list" v-if="goodsInfor.allow_pay_type=='point'">
					<view class="title box-1">星豆抵扣(共{{goodsInfor.points}}星豆)</view>
					<view class="content">
						<u-switch v-model="value" activeColor="#D02227" @change="changeSwitch"></u-switch>
					</view>
				</div>
			</view>
		</view>
		<view class="order-price business-box" v-if="goodsInfor.allow_pay_type == 'transfer_parent'">
			<view class="business-title flex-box">
				<image src="@/static/img/icon-pay.png" class="icon-bus"></image>
				<view class="box-1">
					商家收款码
				</view>
				<view class="flex-box" @click="exchangePay">选择其他支付方式 <u-icon name="arrow-right" color="#BBBBBB"></u-icon></view>
			</view>
			<u-picker title="付款方式" :show="isSelect" :columns="payment"  keyName="label" @confirm="selectPayment" @cancel="exchangePay"></u-picker>
			<view class="business-msg">
				<block v-if="select_info.type == 2">
					<view class="flex-box upload"  >
						<view class="box-1">银行名称</view>
						<view>
							{{select_info.bank_type_name}}
						</view>
					</view>
					<view class="flex-box upload"  >
						<view class="box-1">银行卡号</view>
						<view>
							{{select_info.account_no}}
						</view>
					</view>
				</block>
				<block v-if="select_info.type != 2">
					<view class="code">
						<view class="code-img" v-if="select_info.payment_code" @click="previewImage(select_info.payment_code)">
							<image :src="select_info.payment_code" mode="widthFix" class="icon-img"></image>
						</view>
						<view>{{select_info.label || ''}}支付</view>
						<view class="business-name">
							收款人: {{select_info.name || ''}}
						</view>
					</view>
				</block>
				<view class="flex-box upload"  >
					<view class="box-1">上传支付凭证</view>
					<image :src="pay_img || '../../static/img/camera_img.png'" class="icon-up" @tap="upImg"></image>
				</view>
			</view>
		</view>
		
		<!-- 支付方式列表 -->
		<view class="pay-way" v-if="goodsInfor.allow_pay_type=='cash'">
			<view class="pay_title">
				支付方式
			</view>
			<view class="pay-list">
				<view class="list" v-for="(item,index) in PayList" @click="onPayWay(item,index)" :key="index">
					<view class="pay-type">
						<image :src="item.icon" mode=""></image>
						<text>{{item.name}}</text>
					</view>
					<view class="check">
						<text class="iconfont" :class="PayWay === index ? 'icon-checked action':'icon-check'"></text>
					</view>
				</view>
			</view>
		</view>
		<!-- 地址提示 -->
		<view class="address-tips" :style="scrollTop >= 100 ? '':'display:none'">
			<text>{{addressInfor.address}}</text>
		</view>
		
		</view>
		<!-- 底部合计提交 -->
		<view class="footer-submit">
			<view class="price">
				实际支付
				<text class="min">￥</text>
<!--				<text class="max"
					v-if="value">{{(parseFloat(goodsInfor.points)>=goodsInfor.goods.price?0:(goodsInfor.goods.price-goodsInfor.points)).toFixed(2)}}</text>-->
				<text class="max">{{goodsInfor.total_price.toFixed(2)}}</text>

			</view>
			<view class="submit" @click="onSubmit">
				<text>立即购买</text>
			</view>
		</view>
		<number-jpan :length="6" @closeChange="starBeanFun($event)" :showNum="false" ref="numberPad"></number-jpan>
	</view>
</template>

<script>
	import numberJpan from "../../components/numberJpan/numberJpan.vue";
	import request from "@/utils/request";
	import debounce from "@/utils/debounce.js"
	import { wxconfig } from "@/utils/mixin-wxconfig.js";
	export default {
		mixins:[wxconfig],
		components:{
			numberJpan
		},
		data() {
			return {
				PayList: [{
						icon: '/static/wx_pay.png',
						name: '微信支付',
					},
				],
				isSelect:false,
				PayWay: 0,
				value: true,
				scrollTop: 0,
				addressInfor: {},
				goodsInfor: {
					goods:{
						is_address:0
					},
					total_price:0
				},
				id: 0,
				showNum: true,
				num:1,
				payment:[
					[]
				],
				up_img:'',
				select_info:{},
				flag:true
			};
		},
		computed:{
			pay_img(){
				return (this.up_img instanceof File) ? URL.createObjectURL(this.up_img):''
			},
		},
		onLoad(options) {
			this.id = options.id
			this.getAddress()
			this.getGoodsDetails()
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		methods: {
			previewImage(val){
				wx.ready(()=>{
					wx.previewImage({
					  current: val, // 当前显示图片的http链接
					  urls:[val]
					});
				})
			},
			//获取上级收款信息
			getparentPaycoll(){
				this.$u.api.parentPaycoll()
				.then(res=>{
					let data = res.msg
					if(res.status){
						let num=0
						for(let key in data){
							if(Object.keys(data[key]).length > 0){
								let msg = data[key]
								msg.label = (key=='alipay'?'支付宝':(key=='wechat'?'微信':'银行卡'))
								msg.classify = key
								this.payment[0].push(msg)
							}else{
								num++
							}
						}
						if(num==3){
							this.$u.toast('请联系你的推荐人，添加收款方式')
							return
						}
						this.select_info = this.payment[0][0]
					}
				})
			},
			//显示或隐藏picker
			exchangePay(){
				this.isSelect = !this.isSelect
			},
			//上传凭证
			upImg(){
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const tempFilePaths = res.tempFiles[0];
						const MAX_SIZE = 4 * 1024 * 1024;//2M
						uni.getFileInfo({
						  filePath: res.tempFilePaths[0],
						  success: (infoRes) => {
							if (infoRes.size > MAX_SIZE) {
							 this.$u.toast('图片大于4M，请上传小于4M的图片')
							  return;
							}
							this.up_img = tempFilePaths
						  }
					  })
					}
				})
			},
			selectPayment(e){
				this.select_info = this.payment[0].find(item=>item.type ==  e.value[0].type)
				this.up_img = ''
				this.exchangePay()
			},
			addFun() {
				this.num++
			},
			cutFun() {
				if (this.num > 1) {
					this.num--
				} else {
					uni.showToast({
						icon: 'none',
						title: '不能再减少啦！'
					})
				}
			},
			/**
			 * 支付方式切换点击
			 */
			onPayWay(item, index) {
				this.PayWay = index;
				// this.PayPirce = `${item.name}￥299.00`
			},
			// 默认监听
			changeSwitch(value) {
				console.log(value)
			},
			getGoodsDetails() {
				this.$u.api.ordersPre({
						goods_id: this.id,
						num: 1
					}).then(res => {
						if (res.status) {
							this.goodsInfor = res.msg
							if(res.msg.allow_pay_type == 'transfer_parent'){
								this.getparentPaycoll()
							}
						}
					})
					.catch(err => {
						console.log(err);
					})
			},
			// 获取默认地址
			getAddress() {
				this.$u.api.addressMess().then(res => {

						if (res.status) {
							this.addressInfor = res.msg
						}
					})
					.catch(err => {
						console.log(err);
					})
			},
			/**
			 * 提交订单
			 */
			onSubmit() {
				if(!this.flag){
					this.$u.toast('请勿重复点击')
					return
				}
				//上级收款
				if(this.goodsInfor.allow_pay_type == 'transfer_parent'){
					if(!this.up_img){
						this.$u.toast('请上传支付凭证')
						return
					}
					let _data = {
						goods_id:this.goodsInfor.goods.id,
						address_id:this.addressInfor.id,
						num:this.num,
						payment_imgs:this.up_img,
						payment_type:this.select_info.classify
					}
					uni.showLoading({
						title:'创建订单中……'
					})
					request.requestFormData({
					  url:'/order/orders_create',
					  data:_data,
					}).then((res)=>{
						this.flag = true
						uni.hideLoading()
						if(res.status){
							uni.showModal({
								title:'温馨提醒',
								content:res.msg,
								showCancel:false,
								confirmText:'知道了',
								confirmColor:'#D02227',
								success:(obj)=>{
									if(obj.confirm){
										uni.redirectTo({
											url:`/pages/OrderDetails/OrderDetails?id=${res.data.order_id}`
										})
									}
								}
							})
						}else{
							this.$u.toast(res.msg)
						}
					})
					.catch(err=>{
						uni.hideLoading()
						this.flag = true
					})
					return
				}
				//积分支付
				if(this.goodsInfor.allow_pay_type == 'point'){
					if(!this.value){
						this.$u.toast('请选择星豆抵扣')
						return
					}
					this.$refs.numberPad.open()
					return
				}
				//现金支付
				if(this.goodsInfor.allow_pay_type == 'cash'){
					  let target = navigator.userAgent.toLowerCase();
					  let isWeixin = /micromessenger/.test(target);
					  console.log('是否在微信中打开的',isWeixin);
					if(isWeixin){
						  let _data = {
							goods_id:this.goodsInfor.goods.id,
							address_id:this.addressInfor.id,
							num:this.num,
						  };
						  uni.showLoading({
						  	title:"正在创建订单"
						  })
					  this.$u.api.ordersCreate(_data)
						  .then(res=>{
							this.flag = true
							let _that = this
							uni.hideLoading()
							if(res.status){
							  WeixinJSBridge.invoke(
								  'getBrandWCPayRequest', res.msg.pay_info,
								  function(result){
									if(result.err_msg == "get_brand_wcpay_request:ok" ){
									  // 使用以上方式判断前端返回,微信团队郑重提示：
									  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
									  uni.showToast({
									  	icon:"success",
										title:'支付成功'
									  })
									  setTimeout(()=>{
										  uni.redirectTo({
										  	url:`/pages/OrderDetails/OrderDetails?id=${res.msg.order_id}&back=1`
										  })
									  },1000)
									  return
									}
									if(result.err_msg == "get_brand_wcpay_request:cancel" ){
									  // 使用以上方式判断前端返回,微信团队郑重提示：
									    _that.$u.toast('您已取消支付！')
										setTimeout(()=>{
										  uni.redirectTo({
											url:`/pages/MyOrderList/MyOrderList?type=0`
										  })
										},1000)
										return
									}
								  });
							  return
							}else{
							  _that.$u.toast(res.msg)	
							}

						  })
						  .catch(err=>{
							  uni.hideLoading()
							console.log('err---',err);
							this.flag = true
						  })
						  
				  }else{
					  this.$u.toast('请在微信客户端打开链接')
				  }
						      
				}
			},
			starBeanFun(n){
				uni.showLoading({
					title:'下单中……'
				})
				let _data = {
					goods_id:this.goodsInfor.goods.id,
					address_id:this.addressInfor.id,
					num:this.num,
					pwd:n
				}
				this.$u.api.ordersCreate(_data)
				.then(res=>{
					uni.hideLoading()
					this.flag = true
					if(res.status){
						uni.showModal({
							title:'温馨提醒',
							content:res.msg,
							showCancel:false,
							confirmText:'知道了',
							confirmColor:'#D02227',
							success:(obj)=>{
								if(obj.confirm){
									uni.redirectTo({
										url:`/pages/OrderDetails/OrderDetails?id=${res.data.order_id}`
									})
								}
							}
						})
						return 
					}
					if(res.code == -4){
						uni.showModal({
							title:'温馨提醒',
							content:res.msg,
							showCancel:false,
							confirmText:'去设置密码',
							confirmColor:'#D02227',
							success:(obj)=>{
								if(obj.confirm){
									uni.redirectTo({
										url:`/pages/sub/Setting/change_pwd_pay`
									})
								}
							}
						})
						return 
					}
					uni.showModal({
						title:'温馨提醒',
						content:res.msg,
						showCancel:false,
						confirmColor:'#D02227',
					})
				})
				.catch(err=>{
					console.log(err);
					uni.hideLoading()
					this.flag = true
					uni.hideLoading()
				})
			},
			//数量输入控制
			numFun:debounce.debounce(function(e) {
				if (parseFloat(e.detail.value) < 0) {
					this.$nextTick(() => {
						this.num = 1
					})
				}
			}, 600),
			/**
			 * 跳转点击
			 * @param {String} type 跳转类型
			 */
			onSkip(type) {
				switch (type) {
					case 'address':
						uni.navigateTo({
							url: '/pages/sub/AddressList/AddressList',
						})
						break;
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	@import 'ConfirmOrder.scss';
	@import 'CashierDesk.scss';
</style>